package main

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"

	"fmt"

	"github.com/fsnotify/fsnotify"
)

// NewWatcher 创建监听
func NewWatcher(srcPath, destPath string) {

	paths, err := getPaths(srcPath)
	if err == nil {
		fmt.Println(err)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatalf("Failed to create watcher: %s", err)
	}

	defer watcher.Close()
	done := make(chan bool)

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				fmt.Println(event.Name, " -> ", destPath+event.Name[len(srcPath):])
				err = copyFile(event.Name, destPath+event.Name[len(srcPath):])

			case err := <-watcher.Errors:
				log.Fatalf("Watcher error: %s", err.Error()) // No need to exit here
			}
		}
	}()
	log.Print("Initializing watcher...")
	for _, path := range paths {
		log.Print("Watching: ", path)
		err = watcher.Add(path)
		if err != nil {
			log.Fatalf("Failed to watch directory: %s", err)
		}
	}

	<-done
}

// getPaths 遍历文件夹
func getPaths(srcPath string) (paths []string, err error) {

	err = filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}

		fullPath, _ := filepath.Abs(path)
		if f.IsDir() {
			// fmt.Println(path)
			paths = append(paths, fullPath)
			// return nil
		}

		// if strings.HasSuffix(f.Name(), ".css") {
		// 	fmt.Println(path, destPath+path[len(srcPath):])
		// 	if err := copyFile(path, destPath+path[len(srcPath):]); err != nil {
		// 		log.Fatal(err)
		// 	}
		// }
		return nil
	})
	// if err != nil {
	// 	fmt.Printf("filepath.Walk() returned %v\n", err)
	// }
	return
}

func copyFile(srcFile, destFile string) error {
	file, err := os.Open(srcFile)
	if err != nil {
		return err
	}
	defer file.Close()
	destFilePath := destFile[:strings.LastIndex(destFile, "\\")]
	// if _, err := os.Stat(destFile); os.IsNotExist(err) {
	// 	fmt.Printf("file does not exist")
	// }
	err = os.MkdirAll(destFilePath, 0777)
	if err != nil {
		fmt.Println(err)
	}

	dest, err := os.Create(destFile)
	if err != nil {
		return err
	}
	defer dest.Close()

	if _, err := io.Copy(dest, file); err != nil {
		log.Fatal(err)
	}
	return nil
}

func main() {
	srcPath := filepath.Join("e:/", "b2b-tag")
	destPath := filepath.Join("z:/", "")
	NewWatcher(srcPath, destPath)
}
